package top.jnaw.jee.plugin.shiro;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.utils.ModelResult;


/**
 * Copyright (C) 2018 版权所有。 <p> 文件名： 文件功能描述：
 *
 * @author lc  2018/9/11 15:35 创建内容： <p> <p> 修改标识： 修改原因：
 */
public class UserLevelFilter extends UserFilter {

  protected boolean isAccessAllowed(ServletRequest request,
      ServletResponse response, Object mappedValue) {
    if (isLoginRequest(request, response)) {
      return true;
    } else {
      Subject subject = getSubject(request, response);
      // If principal is not null, then the user is known and should be allowed access.
      return subject.getPrincipal() != null;
    }
  }

  @SuppressWarnings("deprecation")
  protected boolean onAccessDenied(ServletRequest request,
      ServletResponse response) throws Exception {
//    Log.i("@@@@@@@@@@@@@@@");
    //saveRequestAndRedirectToLogin(request, response);
    HttpServletResponse httpResponse;
    HttpServletRequest httpRequest;
    Map<String, Object> map = new HashMap<String, Object>();
    httpResponse = WebUtils.toHttp(response);
    httpRequest = WebUtils.toHttp(request);
    WebUtils.saveRequest(request);
    if (httpRequest.getRequestURI() == null) {
      map.put("requestUri", "");
    } else {
      map.put("requestUri", httpRequest.getRequestURI());
    }
    if (httpRequest.getRequestURL() == null) {
      map.put("requestUrl", "");
    } else {
      map.put("requestUrl", httpRequest.getRequestURL());
      System.out.println(httpRequest.getRequestURL());
    }

    httpResponse.setStatus(200, "redirect");
    httpResponse.setCharacterEncoding("UTF-8");
    httpResponse.setContentType("application/json; charset=utf-8");
    PrintWriter out = null;

    try {
      out = httpResponse.getWriter();
      ModelResult ret = new ModelResult();
      ret.setMessage("用户已过期，请重新登录！");
      ret.setObject(httpResponse.toString());
      ret.setResult(Consts.Result.kUnauthorized);
//      ret.setMap(map);x

      out.append(ret.toJson().toJSONString());
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (out != null) {
        out.close();
      }
    }
    return false;
  }


}